package com.ybwh.springboot2.common.enumhub.enumat;

import com.ybwh.springboot2.common.enumhub.CodeTextEnum;
import com.ybwh.springboot2.common.enumhub.CodeTextEnumUtils;
import com.ybwh.springboot2.common.enumhub.EnumHub;
import com.ybwh.springboot2.common.enumhub.EnumId;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import org.apache.commons.lang3.StringUtils;



/**
 * 自定义的校验注解验证类
 */
public class EnumFieldValidator implements ConstraintValidator<EnumField, Object> {


    private EnumField enumField;

    @Override
    public void initialize(EnumField enumField) {
        this.enumField = enumField;
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        if (value == null) {
            return Boolean.TRUE;
        }

        if (enumField.value() == null) {
            return Boolean.TRUE;
        }

        Class<? extends CodeTextEnum> enumClass = enumField.value();
        EnumId enumId = enumClass.getAnnotation(EnumId.class);
        if (null != enumId) {
            enumClass = EnumHub.getEnumClass(enumId.value());
        }


        String displayName = CodeTextEnumUtils.getDisplayName(enumClass, value);
        if (null != displayName) {
            return true;
        }

        if (StringUtils.isBlank(enumField.message())) {
            //重写错误提示
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate("参数值不在枚举范围,枚举范围：" + CodeTextEnumUtils.getDscr(enumClass) + "。当前值：" + value).addConstraintViolation();
        }

        return false;
    }
}
